<!DOCTYPE html>
<html lang="en">
<?php
// 启动会话
session_start();
?>

<script>
  function userIsLoggedIn() {
    // 在这里实现用户登录状态的检查逻辑
    // 返回值为布尔值，true 表示用户已登录，false 表示用户未登录
    // 示例：检查用户是否具有有效的登录凭据
    // 这里改为检查会话中的登录状态
    return <?php echo isset($_SESSION['loggedin']) && $_SESSION['loggedin'] ? 'true' : 'false'; ?>;
  }

  // 在页面加载时检查用户登录状态
  window.addEventListener('DOMContentLoaded', function() {
    if (!userIsLoggedIn()) {
      window.location.href = '../Login.php';
    }
  });
</script>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>客户管理</title>
  <link rel="stylesheet" href="../css/bootstrap.min.css">
  <link rel="stylesheet" href="../css/bootstrap.min441.css">
  <link href="../css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="../css/jquery-ui.css">
  <link rel="stylesheet" href="../css/bootstrap-select.css">




</head>


<body>
  <div class="container">
    <!-- 预定管理 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <a class="navbar-brand" href="#">酒店后台管理系统</a>
      <!-- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
        aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button> -->
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
          <li class="nav-item ">
            <a class="nav-link" href="./预购订单管理.php">预订管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./房态查询页面.php">房态查询<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./房间状态管理.php">房态管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./后台房源管理页面.php">房源管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item active">
            <a class="nav-link" href="./客户管理页面.php">客户管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item ">
            <a class="nav-link" href="./账户管理页面.php">账户管理<span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="./留言后台查看界面.php">留言管理<span class="sr-only">(current)</span></a>
          </li>


          <li class="nav-item">
            <a class="nav-link" href="../backend01.php">退回主页<span class="sr-only">(current)</span></a>
          </li>

        </ul>
      </div>
    </nav>


    <div class="container">
      <h1>客户管理</h1>
      <button id="addCustomerBtn" class="btn btn-primary mb-3" data-toggle="modal" data-target="#addCustomerModal">添加客户</button>
      <input type="text" id="searchCustomerInput" class="form-control mb-3" placeholder="搜索客户">
      <h1>客户列表</h1>
      <button id="loadCustomersBtn" class="btn btn-warning">加载客户数据</button>
      <table class="table">
        <thead>
          <tr>
            <th>客户ID</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>电话</th>
            <th>职业</th>
            <th>证件类型</th>
            <th>证件号码</th>
            <th>地址</th>
            <th>其它</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="customerList">
          <!-- 这里将会动态生成客户列表 -->
        </tbody>
      </table>
    </div>

    <!-- 添加客户的模态框 -->
    <!-- 添加客户的模态框 -->
    <div class="modal" id="addCustomerModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header ">
            <h4 class="modal-title">添加客户</h4>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
          </div>
          <div class="modal-body">
            <div class="form-group col-md-6">
              <label for="inputName">姓名</label>
              <input type="text" class="form-control" id="inputName">
            </div>
            <div class="form-group col-md-6">
              <label for="inputEmail">邮箱</label>
              <input type="text" class="form-control" id="inputEmail">
            </div>
            <div class="form-group col-md-6">
              <label for="inputPhone">电话</label>
              <input type="text" class="form-control" id="inputPhone">
            </div>
            <div class="form-group col-md-6">
              <label for="inputOccupation">职业</label>
              <input type="text" class="form-control" id="inputOccupation">
            </div>
            <div class="form-group col-md-6">
              <label for="inputIDType">证件类型</label>
              <select class="form-control" id="inputIDType">
                <option value="身份证">身份证</option>
                <option value="护照">护照</option>
                <option value="驾驶证">驾驶证</option>
                <!-- 其他证件类型选项 -->
              </select>
            </div>
            <div class="form-group col-md-6">
              <label for="inputIDNumber">证件号码</label>
              <input type="text" class="form-control" id="inputIDNumber">
            </div>
            <div class="form-group col-md-12">
              <label for="inputAddress">地址</label>
              <input type="text" class="form-control" id="inputAddress">
            </div>
            <div class="form-group col-md-12">
              <label for="inputOther">其它</label>
              <textarea class="form-control" id="inputOther"></textarea>
            </div>
          </div>
          <div class="modal-footer col-md-12">
            <button type="button" class="btn btn-success" id="saveCustomerBtn">保存</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
          </div>
        </div>
      </div>
    </div>



    <!-- 编辑客户的模态框 -->
    <!-- 编辑客户的模态框 -->
    <div class="modal" id="editCustomerModa2">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">编辑客户</h4>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
          </div>
          <div class="modal-body">
            <input type="hidden" id="editCustomerId">
            <div class="form-group">
              <label for="editName">姓名</label>
              <input type="text" class="form-control" id="editName">
            </div>
            <div class="form-group">
              <label for="editPhone">电话</label>
              <input type="text" class="form-control" id="editPhone">
            </div>
            <!-- 添加新的输入框和下拉框 -->
            <div class="form-group">
              <label for="editEmail">邮箱</label>
              <input type="text" class="form-control" id="editEmail">
            </div>
            <div class="form-group">
              <label for="editOccupation">职业</label>
              <input type="text" class="form-control" id="editOccupation">
            </div>
            <div class="form-group">
              <label for="editIdType">证件类型</label>
              <select class="form-control" id="editIdType">
                <option value="身份证">身份证</option>
                <option value="护照">护照</option>
                <option value="驾驶证">驾驶证</option>
                <!-- 其他证件类型选项 -->
              </select>
            </div>
            <div class="form-group">
              <label for="editIdNumber">证件号码</label>
              <input type="text" class="form-control" id="editIdNumber">
            </div>
            <div class="form-group">
              <label for="editAddress">地址</label>
              <input type="text" class="form-control" id="editAddress">
            </div>
            <div class="form-group">
              <label for="editOther">其它</label>
              <input type="text" class="form-control" id="editOther">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-success" id="updateCustomerBtn">更新</button>
            <button type="button" class="btn btn-secondary" id="closeCustomerBtn" data-dismiss="modal">关闭</button>
          </div>
        </div>
      </div>
    </div>

    <script src="../js/jquery-3.5.1.min.js"></script>
    <script src="../js/bootstrap.min441.js"></script>


    <script>
      // 单例方式设置全局变量
      // 将customers数组封装在了名为App的单例对象内部。通过将其定义为App.customers，可以在任何地方访问到
      var App = {
        customers: [], // 全局变量
        init: function() {
          var self = this;
          $(document).ready(function() {
            $('#loadCustomersBtn').click(function() {
              $.ajax({
                url: '../backend/api/customerManagementPage_2.php',
                type: 'GET',
                success: function(data) {
                  self.customers = JSON.parse(data);
                  self.generateCustomerList(self.customers);
                  console.log(self.customers);
                  console.log(self.customers.length);
                },
                error: function() {
                  console.log('加载客户数据失败');
                }
              });
            });
          });
        },
        generateCustomerList: function(customers) {
          $('#customerList').empty();
          customers.forEach(function(customer) {
            var customerId = customer.customer_id ? customer.customer_id : "undefined"; // 检查 customer.customer_id 的值
            var customerItem = $('<tr><td>' + customer.customer_id + '</td><td>' + customer.name + '</td><td>' + customer.email + '</td><td>' + customer.phone + '</td><td>' + customer.occupation + '</td><td>' + customer.idType + '</td><td>' + customer.idNumber + '</td><td>' + customer.address + '</td><td>' + customer.other + '</td><td><button class="btn btn-primary mr-2 editCustomerBtn" data-custom-id="' + customerId + '" data-bs-toggle="modal" data-bs-target="#editCustomerModa2">编辑</button><button class="btn btn-danger deleteCustomerBtn" data-customer-id="' + customer.customer_id + '">删除</button></td></tr>');
            // ↑ 将 `data-customer-id` 属性值设为 customerId，并且创建了 `data-custom-id` 自定义属性
            customerItem.data('customer-id', customerId); // 将 customerId 存储在 data-customer-id 中
            $('#customerList').append(customerItem);
          });
        }
      };

      // 初始化应用程序
      App.init();


      // 普通方式设置，不要删！！！！！！！！（警示代码）
      // $(document).ready(function () {
      //   $('#loadCustomersBtn').click(function () {
      //     $.ajax({
      //       url: '../backend/api/customerManagementPage_2.php',  // 指向你的PHP文件路径
      //       type: 'GET',
      //       success: function (data) {
      //         var customers = JSON.parse(data);  // 将JSON格式的响应转换为JavaScript对象
      //         generateCustomerList(customers);  // 通过调用generateCustomerList函数将数据插入到页面中
      //         console.log(customers);
      //         console.log(customers.length);
      //       },
      //       error: function () {
      //         console.log('加载客户数据失败');
      //       }
      //     });
      //   });
      //   function generateCustomerList(customers) {
      //     $('#customerList').empty();
      //     customers.forEach(function (customer) {
      //       var customerItem = $('<tr><td>' + customer.customer_id + '</td><td>' + customer.name + '</td><td>' + customer.email + '</td><td>' + customer.phone + '</td><td>' + customer.occupation + '</td><td>' + customer.idType + '</td><td>' + customer.idNumber + '</td><td>' + customer.address + '</td><td>' + customer.other + '</td><td><button class="btn btn-primary mr-2 editCustomerBtn" data-customer-id="' + customer.id + '" data-bs-toggle="modal" data-bs-target="#editCustomerModal">编辑</button><button class="btn btn-danger deleteCustomerBtn" data-customer-id="' + customer.id + '">删除</button></td></tr>');
      //       $('#customerList').append(customerItem);
      //     });
      //   }
      // });

      // 添加客户
      // 添加客户

      $('#saveCustomerBtn').on('click', function() {
        var name = $('#inputName').val();
        var email = $('#inputEmail').val();
        var phone = $('#inputPhone').val();
        var occupation = $('#inputOccupation').val();
        var idType = $('#inputIDType').val();
        var idNumber = $('#inputIDNumber').val();
        var address = $('#inputAddress').val();
        var other = $('#inputOther').val();
        $.ajax({
          url: '../backend/api/customerManagementPage_1.php',
          method: 'POST',
          data: {
            name: name,
            email: email,
            phone: phone,
            occupation: occupation,
            idType: idType,
            idNumber: idNumber,
            address: address,
            other: other
          },
          success: function(response) {
            console.log(response); // 输出后端返回的响应
            $('#inputName').val('');
            $('#inputEmail').val('');
            $('#inputPhone').val('');
            $('#inputOccupation').val('');
            $('#inputIDType').val('');
            $('#inputIDNumber').val('');
            $('#inputAddress').val('');
            $('#inputOther').val('');
            $('#addCustomerModal').modal('hide');
            // generateCustomerList(); // 可以在上传成功后进行客户列表的刷新等操作
          },
          error: function(xhr, status, error) {
            console.log('发生错误：' + error);
          }
        });
      });
      // // // 打开模态框 
      $(document).on('click', '.editCustomerBtn', function() {
        $('#editCustomerModa2').modal('show');
        console.log(App.customers);
        var customerId = $(this).data('custom-id');
        console.log(customerId);
        var customer = App.customers.find(c => c.customer_id === customerId);
        console.log(customer.name);
        if (customer) {
          // 在这里执行编辑操作
          // 例如显示编辑模态框并在模态框中填充客户信息

          console.log(customer);
          $('#editCustomerId').val(customer.customer_id);
          $('#editName').val(customer.name);
          $('#editName').val(customer.name);
          $('#editEmail').val(customer.email);
          $('#editPhone').val(customer.phone);
          $('#editOccupation').val(customer.occupation);
          $('#editIdType').val(customer.idType);
          $('#editIdNumber').val(customer.idNumber);
          $('#editAddress').val(customer.address);
          $('#editOther').val(customer.other);
        }
      });
      // 更新操作
      $('#updateCustomerBtn').on('click', function() {
        var id = $('#editCustomerId').val();
        console.log(id);
        var newName = $('#editName').val();
        var newEmail = $('#editEmail').val();
        var newPhone = $('#editPhone').val();
        var newOccupation = $('#editOccupation').val();
        var newIdType = $('#editIdType').val();
        var newIdNumber = $('#editIdNumber').val();
        var newAddress = $('#editAddress').val();
        var newOther = $('#editOther').val();
        console.log("到这一步了1");
        console.log(App.customers);

        var customerIndex = App.customers.findIndex(c => c.customer_id == id);
        console.log(customerIndex);
        console.log("到这一步了2");
        if (customerIndex !== -1) {
          App.customers[customerIndex].name = newName;
          App.customers[customerIndex].email = newEmail;
          App.customers[customerIndex].phone = newPhone;
          App.customers[customerIndex].occupation = newOccupation;
          App.customers[customerIndex].idType = newIdType;
          App.customers[customerIndex].idNumber = newIdNumber;
          App.customers[customerIndex].address = newAddress;
          App.customers[customerIndex].other = newOther;
          // self.generateCustomerList(App.customers);

          console.log("到这一步了3");
          // 关闭模态框
          $('#editCustomerModal').modal('hide');
          $.ajax({
            url: '../backend/api/customerManagementPage_3.php',
            method: 'POST',
            data: {
              id: id,
              name: newName,
              email: newEmail,
              phone: newPhone,
              occupation: newOccupation,
              idType: newIdType,
              idNumber: newIdNumber,
              address: newAddress,
              other: newOther
            },
            success: function(response) {
              // 处理服务器响应
              console.log(response);
              // 根据需要执行其他操作，例如更新页面显示或者显示成功更新的消息
            },
            error: function(xhr, status, error) {
              // 处理错误
              console.log(error);
            }
          });


        }
      });

      // 当点击更新按钮时，顺手执行刷新按钮updateCustomerBtn
      $('updateCustomerBtn').click(function() {
        $.ajax({
          url: '../backend/api/customerManagementPage_2.php',
          type: 'GET',
          success: function(data) {
            self.customers = JSON.parse(data);
            self.generateCustomerList(self.customers);
            console.log(self.customers);
            console.log(self.customers.length);
          },
          error: function() {
            console.log('加载客户数据失败');
          }
        });
      })

      // 当点击关闭按钮时，顺手执行刷新按钮
      $('closeCustomerBtn').click(function() {
        $.ajax({
          url: '../backend/api/customerManagementPage_2.php',
          type: 'GET',
          success: function(data) {
            self.customers = JSON.parse(data);
            self.generateCustomerList(self.customers);
            console.log(self.customers);
            console.log(self.customers.length);
          },
          error: function() {
            console.log('加载客户数据失败');
          }
        });
      })
      // 删除客户按钮点击事件
      $(document).on('click', '.deleteCustomerBtn', function() {
        var customerId = $(this).data('customer-id');
        var customerName = App.customers.find(c => c.customer_id == customerId).name;
        // 删除打印测试
        console.log("删除打印测试");
        console.log(customerId);
        console.log(customerName);
        // 弹出确认对话框
        var confirmDelete = confirm("确认删除客户" + customerName + "吗？");
        if (confirmDelete) {
          $.ajax({
            url: '../backend/api/customerManagementPage_4.php',
            type: 'POST',
            data: {
              customer_id: customerId
            },
            success: function(response) {
              // 更新客户列表
              App.customers = App.customers.filter(c => c.customer_id !== customerId);
              App.generateCustomerList(App.customers);
            },
            error: function() {
              console.log('删除客户失败');
            }
          });
        }
      });


      // // // 搜索客户
      $('#searchCustomerInput').on('input', function() {
        var searchTerm = $(this).val(); // 获取用户输入的搜索条件
        filterCustomers(searchTerm); // 调用 filterCustomers() 函数进行客户列表过滤
      });

      // 过滤客户列表
      function filterCustomers(searchTerm) {
        // 使用 filter() 方法过滤客户列表
        var filteredCustomers = App.customers.filter(function(customer) {
          // 在这里添加根据搜索条件过滤的逻辑
          // 这里可以使用 String.prototype.includes() 方法来进行模糊搜索
          // 示例代码：根据客户名称或邮箱进行搜索
          return customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            customer.email.toLowerCase().includes(searchTerm.toLowerCase());
        });

        // 重新生成过滤后的客户列表
        App.generateCustomerList(filteredCustomers);
      }
    </script>
</body>

</html>